module utils_misc_mod

use global_mod

implicit none

integer(kind=ink), parameter :: ARROW_ERR_PAR_INVAL   = 1001 !< error code for an invalid parameter
integer(kind=ink), parameter :: ARROW_ERR_MEM_ASSOC   = 2001 !< error code for failed pointer association
integer(kind=ink), parameter :: ARROW_ERR_MEM_ALLOC   = 2002 !< error code for failed memory allocation
integer(kind=ink), parameter :: ARROW_ERR_MEM_DEALLOC = 2003 !< error code for failed memory deallocation
integer(kind=ink), parameter :: ARROW_ERR_DMP_VTKINI  = 3001 !< error code for VTK graphics dump init
integer(kind=ink), parameter :: ARROW_ERR_DMP_VTKMSH  = 3002 !< error code for VTK graphics dump mesh
integer(kind=ink), parameter :: ARROW_ERR_DMP_VTKCLS  = 3003 !< error code for VTK graphics dump close
integer(kind=ink), parameter :: ARROW_ERR_VAR_FIND    = 4001 !< error code for variable not found
integer(kind=ink), parameter :: ARROW_ERR_VAR_GET     = 4002 !< error code for variable not returned
integer(kind=ink), parameter :: ARROW_ERR_PON_FORM    = 5001 !< error code for Paint On form unknown
integer(kind=ink), parameter :: ARROW_ERR_PON_FUNC    = 5002 !< error code for Paint On function unknown

contains

!> Interpret an error code, currently just
!> prints out a message.
subroutine Print_ErrCode(err_code)
  integer(kind=ink),  intent(in) :: err_code
  select case(err_code)
    case(ARROW_ERR_PAR_INVAL)
      write(6,*) "PARAMETER: Invalid parameter"
    case(ARROW_ERR_MEM_ASSOC)
      write(6,*) "MEMORY: Pointer association failed"
    case(ARROW_ERR_MEM_ALLOC)
      write(6,*) "MEMORY: Allocation attempt failed"
    case(ARROW_ERR_MEM_DEALLOC)
      write(6,*) "MEMORY: Deallocation attempt failed"
    case(ARROW_ERR_DMP_VTKINI)
      write(6,*) "DUMP: VTK Initialisation failed"
    case(ARROW_ERR_DMP_VTKMSH)
      write(6,*) "DUMP: VTK Mesh write failed"
    case(ARROW_ERR_DMP_VTKCLS)
      write(6,*) "DUMP: VTK Close failed"
    case(ARROW_ERR_VAR_FIND)
      write(6,*) "VAR: Variable unknown in find"
    case(ARROW_ERR_VAR_GET)
      write(6,*) "VAR: Variable unknown in get"
    case(ARROW_ERR_PON_FORM)
      write(6,*) "PAINTON: form unknown"
    case(ARROW_ERR_PON_FUNC)
      write(6,*) "PAINTON: function unknown"
    case default
      write(6,*) "UNKNOWN ERROR - Yeah, you read that right, UNKNOWN"
  end select
end subroutine Print_ErrCode

!> Handle a critical error by printing out a few bits
!> and the stopping hard.
subroutine Critical_Error(err_code, routine)
  integer(kind=ink), intent(in) :: err_code
  character(len=*),  intent(in) :: routine
  write(6,*) "CRITICAL ERROR in routine:", trim(routine)
  call Print_ErrCode(err_code)
  stop
end subroutine Critical_Error

end module utils_misc_mod